package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 23 5月 2025 16:36
 */
@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    private Map<String, Object> getBaseMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        return map;
    }

    /**
     * 根据临时凭证码（openId获取专用凭证码）获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> baseMap = getBaseMap();
        baseMap.put("js_code", code);
        baseMap.put("grant_type", "authorization_code");
        //发送请求给微信服务器获取openId
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", baseMap);
        //返回的是一个JSON字符串 需要解析拿到对应的openid 获取json对象
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getString("errcode") != null && Integer.valueOf(jsonObject.getString("errcode")) != 0) {
            throw new BaseException("获取openId失败");
        }
        return jsonObject.getString("openid");
    }


    /**
     * 根据临时凭证码（手机号获取专用凭证码，非openId凭证码）获取手机号
     *
     * @return
     */
    public String getAccessToken() {
        Map<String, Object> baseMap = getBaseMap();
        baseMap.put("grant_type", "client_credential");
        String access_token = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", baseMap);
        if (StrUtil.isBlank(access_token)) {
            throw new BaseException("获取access_token失败");
        }
        JSONObject jsonObject = JSON.parseObject(access_token);
        return jsonObject.getString("access_token");

    }


    /**
     * 获取手机号
     */
    @Override
    public String getPhone(String code) {
        //获取access_token临时凭证
        String accessToken = getAccessToken();
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("code", code);
        //官方文档 参数是String类型
        String result = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken,
                JSON.toJSONString(baseMap));
        if (StrUtil.isBlank(result)) {
            throw new BaseException("获取手机号失败");
        }
        //获取手机号
        JSONObject jsonObject = JSON.parseObject(result);
        String phoneInfoJSON = jsonObject.getString("phone_info");
        if (StringUtils.isNotBlank(phoneInfoJSON)) {
            JSONObject phoneObject = JSONObject.parseObject(phoneInfoJSON);
            return phoneObject.getString("phoneNumber");
        }
        return null;
    }
}
